﻿package src.game.managers{
	import src.sound.SoundPlayer;
	import flash.events.Event;
	
	public class SoundManager {
		private var sounds:Vector.<SoundPlayer>;
		private static var instance:SoundManager;
		private var sound:Boolean;
		
		public function SoundManager() {
			if( instance ) throw new Error( "Dostęp do klasy jedynie za pośrednictwem metody Singleton.getInstance()" );
			trace ("wektor");
			sounds = new Vector.<SoundPlayer>;
			sound = true;
		}
		
		public static function getInstance():SoundManager {
			if (instance == null) instance = new SoundManager();
			return instance;
		}
		
		public function add(sound:SoundPlayer):void {
			sounds.push(sound);
			if ( !this.sound) sound.setVolume(0); 
			sound.addEventListener(Event.SOUND_COMPLETE, endSound);
			sound.play();
		}
		
		private function endSound(event:Event):void {
			var s:SoundPlayer = (SoundPlayer)(event.target);
			if (s.isRepetable() ) s.play();
			else {
				s.removeEventListener(Event.SOUND_COMPLETE, endSound);
				remove(s);
			}
		}
		
		public function removeAt(index:int):void {
			trace ("sound removed");
			sounds.splice(index, 1);
		}
		
		public function remove(sound:SoundPlayer):void {
			var index:int = sounds.indexOf(sound);
			if (index >= 0) removeAt(index);
		}
		
		public function setSound(value:Boolean):void {
			sound = value;
			(sound == true) ? setVolume(1) : setVolume(0); 
		}
		
		public function getSound():Boolean {
			return sound;
		}
		
		public function setVolume(value:Number):void {
			for each (var item:SoundPlayer in sounds) {
				item.setVolume(value);
			}
		}
	}
	
}
